﻿using Adp;
using Adp.Common;
using Adp.Core.Attribute;
using Microsoft.AspNetCore.Mvc;
using Yqd.Core;
using Yqd.Enm;
using Yqd.Models;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.IO;
using System.Threading;

namespace Yqd.Controllers
{
    public class DepartmentController : BaseController
    {
        YqdContext ctx;
        DdService ddService;
        static string UnitCode = "";
        static string UnitName = "";

        public DepartmentController(YqdContext ctx, DdService ddService)
        {
            this.ctx = ctx;
            this.ddService = ddService;
        }

        public ActionResult GetList()
        {
            var ParentCode = Form.GetString("ParentCode");
            var Paths = Form.GetString("Paths");
            var Fullname = Form.GetString("Fullname");

            return this.ToJson(new
            {
                success = true,
                data = from q in ctx.Yqd_Department.Where(it => it.ParentCode == ParentCode)
                       select new
                       {
                           q.OrganizationCode,
                           label = q.Name,
                           isLeaf = q.isLeaf,
                           Paths = (Paths + "." + q.OrganizationCode).Trim('.'),
                           Fullname = (Fullname + ">" + q.Name).Trim('>')
                       }
            });
        }

        public ActionResult GetUnitList()
        {
            var start = Form.GetInt("start");
            var limit = Form.GetInt("limit");
            var key = Form.GetString("key");
            var unbind = Form.GetBool("unbind", false);
            var where = "[UnitCode]!='330782000000'";
            if (key.Trim() != "")
            {
                where += " and lower(ltrim(rtrim([Name]))) like {0}";
            }
            if (unbind)
            {
                where += " and (OrganizationCode is null or OrganizationCode='')";
            }
            var (totalcount, data) = ctx.Database.SqlPager<Yqd_Unit>(start, limit, "*", where, "[Tactic] asc", "%" + key.ToLower().Trim() + "%");
            var ds = ctx.Yqd_Department.Where(it => it.TypeCode == "GOV_UNIT").Select(it => new { it.OrganizationCode, it.Name }).ToList();
            return this.ToJson(new
            {
                success = true,
                totalcount,
                data = data.Select(q => new
                {
                    q.ID,
                    Dept = q.Name,
                    q.OrganizationCode,
                    Name = ds.FirstOrDefault(it => it.OrganizationCode == q.OrganizationCode)?.Name ?? ""
                })
            });
        }

        public ActionResult GetDeptList()
        {
            var key = Form.GetString("key");
            var r = ctx.Yqd_Department.Where(it => it.TypeCode == "GOV_UNIT");
            if (key.Trim() != "")
            {
                r = r.Where(it => it.Name.ToLower().Trim().Contains(key.ToLower().Trim()));
            }
            return this.ToJson(new
            {
                success = true,
                data = r.Select(it => new
                {
                    ID = it.OrganizationCode,
                    label = it.Name,
                    isLeaf = true,
                    Paths = it.OrganizationCode.ToString()
                })
            });
        }

        public ActionResult GetUserList()
        {
            var OrganizationCode = Form.GetString("OrganizationCode");
            var Fullname = Form.GetString("Fullname");

            var config = Config.AppSecret(AccessTokenMode.浙政钉通讯录);
            var arr = ddService.pageOrganizationEmployeeCodes(OrganizationCode, config.TenantId);
            var r = new ArrayList();
            foreach (var item in arr)
            {
                var o = ddService.GetEmployeeInfo(item, config.TenantId);
                o["empJobLevelName"] = ddService.GetPropertyNameByCode("职级", o["empJobLevelCode"].ToString());
                o["Role"] = 角色类型.未设置.ToString();
                o["Permit"] = "未设置";
                o["Status"] = 0;
                o["OrganizationCode"] = OrganizationCode;
                o["OrganizationName"] = Fullname;
                var eu = ctx.Yqd_User.FirstOrDefault(it => it.EmployeeCode == o["employeeCode"].ToString());
                if (eu != null)
                {
                    o["Status"] = (int)eu.Status;
                    o["Role"] = string.Join(',', eu.Roles.Split(",").Select(it => (角色类型)int.Parse(it)));
                    o["Permit"] = string.Join(',', eu.PermitItem.Split(",").Select(it => (权限清单)int.Parse(it)));
                }
                r.Add(o);
            }
            return this.ToJson(new
            {
                success = true,
                data = r
            });
        }
        public ActionResult SearchUserList()
        {
            var key = Form.GetString("key");
            var role = Form.GetInt("role", -1);
            var permit = Form.GetInt("permit", -1);
            var r = ctx.Yqd_User.AsEnumerable();
            if (key.HasValue())
            {
                r = r.Where(it => it.Name.Contains(key));
            }
            if (role > -1)
            {
                r = r.Where(it => ("," + it.Roles + ",").Contains("," + role + ","));
            }
            if (permit > -1)
            {
                r = r.Where(it => ("," + it.PermitItem + ",").Contains("," + permit + ","));
            }
            return this.ToJson(new
            {
                success = true,
                data = from q in r.ToList()
                       select new
                       {
                           employeeName = q.Name,
                           employeeCode = q.EmployeeCode,
                           q.empJobLevelCode,
                           q.empBudgetedPostCode,
                           q.empJobLevelName,
                           Role = !string.IsNullOrWhiteSpace(q.Roles)? string.Join(',', q.Roles.Split(",").Select(it => (角色类型)int.Parse(it))):"",
                           Permit = !string.IsNullOrWhiteSpace(q.PermitItem) ? string.Join(',', q.PermitItem.Split(",").Select(it => (权限清单)int.Parse(it))):"",
                           q.Status,
                           q.OrganizationCode,
                           q.OrganizationName
                       }
            });
        }
        public ActionResult GetUserList1()
        {
            var OrganizationCode = Form.GetString("OrganizationCode");

            return this.ToJson(new
            {
                success = true,
                data = from q in ctx.Yqd_User.Where(it => it.OrganizationCode == OrganizationCode)
                       select new
                       {
                           q.empBudgetedPostCode,
                           q.Name,
                           q.empJobLevelName,
                           Role = q.Roles
                       }
            });
        }

        public ActionResult GetLogList()
        {
            var start = Form.GetInt("start");
            var limit = Form.GetInt("limit");
            var key = Form.GetString("key");
            var sdate = Form.GetDateTime("sdate", DateTime.MinValue);
            var edate = Form.GetDateTime("edate", DateTime.MinValue);
            var r = ctx.Yqd_Logging.AsQueryable();
            var user = ctx.Yqd_User.ToList();
            if (key.HasValue())
            {
                var codes = user.Where(it => it.Name.Trim().Contains(key.Trim()) || it.OrganizationName.Trim().Contains(key.Trim())).Select(it => it.EmployeeCode).ToArray();
                r = r.Where(it => codes.Contains(it.EmployeeCode));
            }
            if (sdate != DateTime.MinValue)
            {
                r = r.Where(it => it.Instime > sdate);
            }
            if (edate != DateTime.MinValue)
            {
                var ed = edate.AddDays(1);
                r = r.Where(it => it.Instime < ed);
            }
            Yqd_User su = null;
            return this.ToJson(new
            {
                success = true,
                totalcount = r.Count(),
                data = r.OrderByDescending(it=>it.Instime).Skip(start).Take(limit).ToList().Select(q => new
                {
                    employeeName = (su = user.FirstOrDefault(it => it.EmployeeCode == q.EmployeeCode)).Name,
                    employeeCode = q.EmployeeCode,
                    su.empJobLevelName,
                    Role = !string.IsNullOrWhiteSpace(su.Roles) ? string.Join(',', su.Roles.Split(",").Select(it => (角色类型)int.Parse(it))) : "",
                    Permit = !string.IsNullOrWhiteSpace(su.PermitItem) ? string.Join(',', su.PermitItem.Split(",").Select(it => (权限清单)int.Parse(it))) : "",
                    su.OrganizationName,
                    Instime = q.Instime.ToString("yyyy-MM-dd HH:mm:ss")
                })
            });
        }

        public ActionResult SetRole()
        {
            var Employees = Form.GetString("Employees").ToJArray();
            var Role = Form.GetString("Role");
            var PermitItem = Form.GetString("PermitItem", "");
            var wx = Config.AppSecret(AccessTokenMode.浙政钉通讯录);
            foreach (var info in Employees)
            {
                var employeeCode = info["employeeCode"].ToString();
                var OrganizationCode = info["OrganizationCode"].ToString();
                var emp = ctx.Yqd_User.FirstOrDefault(it => it.EmployeeCode == employeeCode);
                var empJobLevelCode = info["empJobLevelCode"]?.ToString() ?? "";
                var empBudgetedPostCode = info["empBudgetedPostCode"]?.ToString() ?? "";
                var unit = GetUnit(OrganizationCode);
                if (emp == null)
                {
                    emp = new Yqd_User
                    {
                        AccountId = 0,
                        Openid = "",
                        Roles = Role,
                        PermitItem = PermitItem == "" ? "0" : PermitItem,
                        EmployeeCode = employeeCode,
                        Name = info["employeeName"].ToString(),
                        Avatar = info["govEmpAvatar"]?.ToString() ?? "",
                        Gender = info["empGender"].ToString().ToInt(),
                        OrganizationCode = OrganizationCode,
                        OrganizationName = info["OrganizationName"].ToString(),
                        UnitCode = unit.UnitCode,
                        UnitName = unit.UnitName,
                        empJobLevelCode = empJobLevelCode,
                        empBudgetedPostCode = empBudgetedPostCode,
                        empJobLevelName = ddService.GetPropertyNameByCode("职级", empJobLevelCode),
                        empBudgetedPostName = ddService.GetPropertyNameByCode("人员编制", empBudgetedPostCode),
                        Status = 用户状态.使用中,
                        Instime = DateTime.Now
                    };
                    ctx.Yqd_User.Add(emp);
                }
                else
                {
                    emp.Roles = Role;
                    if (PermitItem != "")
                        emp.PermitItem = PermitItem;
                    emp.Name = info["employeeName"].ToString();
                    if (info["govEmpAvatar"] != null)
                    {
                        emp.Avatar = info["govEmpAvatar"].ToString();
                    }
                    if (info["empGender"] != null)
                    {
                        emp.Gender = info["empGender"].ToString().ToInt();
                    }
                    emp.OrganizationCode = info["OrganizationCode"].ToString();
                    emp.OrganizationName = info["OrganizationName"].ToString();
                    emp.empJobLevelCode = empJobLevelCode;
                    emp.UnitCode = unit.UnitCode;
                    emp.UnitName = unit.UnitName;
                    emp.empBudgetedPostCode = empBudgetedPostCode;
                    emp.empJobLevelName = ddService.GetPropertyNameByCode("职级", empJobLevelCode);
                    emp.empBudgetedPostName = ddService.GetPropertyNameByCode("人员编制", empBudgetedPostCode);
                    emp.Instime = DateTime.Now;
                }
                if (emp.AccountId == 0)
                {
                    var AccountId = ddService.listEmployeeAccountIds(emp.EmployeeCode, wx.TenantId);
                    if (AccountId?["accountId"] != null)
                    {
                        emp.AccountId = AccountId["accountId"].ToString().ToInt();
                    }
                }
            }
            var ret = ctx.SaveChanges();
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }

        private (string UnitCode, string UnitName) GetUnit(string OrganizationCode)
        {
            var org = ctx.Yqd_Department.FirstOrDefault(it => it.OrganizationCode == OrganizationCode);
            if (org == null)
            {
                return ("", "");
            }
            if (org.TypeCode == "GOV_UNIT")
            {
                UnitCode = org.OrganizationCode;
                UnitName = org.Name;
            }
            if (org.TypeCode == "GOV_HOLLOW_STRIP_NODE")
            {
                return (UnitCode, UnitName);
            }
            return GetUnit(org.ParentCode);
        }

        public ActionResult SetState()
        {
            var Employees = Form.GetStringArray("Employees[]");
            var state = Form.GetInt("state");
            var user = ctx.Yqd_User.Where(it => Employees.Contains(it.EmployeeCode));
            foreach(var u in user)
            {
                u.Status = (用户状态)state;
            }
            var ret = ctx.SaveChanges();
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }

        public ActionResult UpdateAvatar()
        {
            var EmployeeCode = Form.GetString("EmployeeCode");
            var rootPath = Env.ServerRoot.Combine("wwwroot");
            var filepath = "/Client/Yqd/Avatar/";
            var path = rootPath + filepath;
            if (!Directory.Exists(path)) Directory.CreateDirectory(path);
            var ret = 0;
            var user = ctx.Yqd_User.FirstOrDefault(it => it.EmployeeCode == EmployeeCode);
            if (user != null)
            {
                var filename = user.EmployeeCode + ".jpg";
                var fpath = path + filename;
                if (System.IO.File.Exists(fpath)) System.IO.File.Delete(fpath);
                if (!string.IsNullOrWhiteSpace(user.Avatar))
                {
                    var bl = ddService.GenerateAvatar(user.Avatar, fpath);
                    ret = bl ? 1 : 0;
                }
            }
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }

        public ActionResult refresh()
        {
            var ParentCode = Form.GetString("OrganizationCode");
            var Paths = Form.GetString("Paths");
            var Fullname = Form.GetString("Fullname");

            var config = Config.AppSecret(AccessTokenMode.浙政钉通讯录);
            List<string> arr;
            if (ParentCode.HasValue())
            {
                arr = ddService.pageSubOrganizationCodes(ParentCode, config.TenantId);
            }
            else
            {
                arr = ddService.scopesV2(config.TenantId)["deptVisibleScopes"].Select(it => it.ToString()).ToList();
            }
            var r = new ArrayList();
            foreach (var item in arr)
            {
                var info = ddService.GetOrganizationInfo(item, config.TenantId);
                var isLeaf = ddService.pageSubOrganizationCodes(item, config.TenantId, true).Count == 0;
                var code = info["institutionLevelCode"]?.ToString() ?? "";
                var organizationCode = info["organizationCode"].ToString();
                var org = ctx.Yqd_Department.FirstOrDefault(it => it.OrganizationCode == organizationCode);
                if (org == null)
                {
                    ctx.Yqd_Department.Add(new Yqd_Department
                    {
                        OrganizationCode = organizationCode,
                        ParentCode = ParentCode,
                        Name = info["organizationName"].ToString(),
                        InstitutionLevelCode = code,
                        InstitutionLevelName = ddService.GetPropertyNameByCode("单位级别", code),
                        TypeCode = info["typeCode"]?.ToString() ?? "",
                        TypeName = info["typeName"]?.ToString() ?? "",
                        isLeaf = isLeaf

                    });
                }
                else
                {
                    org.Name = info["organizationName"].ToString();
                    org.InstitutionLevelCode = code;
                    org.InstitutionLevelName = ddService.GetPropertyNameByCode("单位级别", code);
                    org.TypeCode = info["typeCode"]?.ToString() ?? "";
                    org.TypeName = info["typeName"]?.ToString() ?? "";
                    org.isLeaf = isLeaf;
                }
                ctx.SaveChanges();
            }
            var dep = ctx.Yqd_Department.FirstOrDefault(it => it.OrganizationCode == ParentCode);
            return this.ToJson(new
            {
                success = true,
                parent = dep?.ParentCode,
                current = ParentCode
            });
        }
        public ActionResult GetRoleList()
        {
            var roles = new List<object>();
            var aroles = new List<object>();
            var types = typeof(角色类型);
            foreach (int item in Enum.GetValues(types))
            {
                if (item < (int)角色类型.协调人)
                    roles.Add(new { name = Enum.GetName(types, item), value = item.ToString() });
                else
                    aroles.Add(new { name = Enum.GetName(types, item), value = item.ToString() });
            }
            return this.ToJson(new
            {
                success = true,
                roles,
                aroles
            });
        }

        public ActionResult GetPermitList()
        {
            return this.ToJson(new
            {
                success = true,
                data = from q in Enum.GetNames(typeof(权限清单))
                       select new
                       {
                           value = Enum.Parse(typeof(权限清单), q),
                           name = q
                       }
            });
        }

        public ActionResult SetRelation()
        {
            var UnitID = Form.GetInt("UnitID");
            var OrgCode = Form.GetString("OrgCode");
            var ret = ctx.Database.ExecuteSql("update Yqd_Unit set OrganizationCode={1} where ID={0}", UnitID, OrgCode);
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }

        public ActionResult Delete()
        {
            var Employees = Form.GetStringArray("Employees[]");
            var user = ctx.Yqd_User.Where(it => Employees.Contains(it.EmployeeCode));
            ctx.Yqd_User.RemoveRange(user);
            var ret = ctx.SaveChanges();
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }
    }
}
